import os
import sys
import shutil
import logging

sys.path.insert(0, os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir))

from base.context import Context
from utils.db_object_pool import DBObjectPool
from utils.common_utils import file_md5
from configure.config_logging import capture_log_init

class FileChangeHandler(object):
    def __init__(self):
        self.context = Context()
        self.env = {}
        self.cache_db_handler = None
        self.gcc_db_handler = None
        self.clang_db_handler = None

    def init_runtime_env(self):
        self.env = dict(os.environ)
        self.context.update_work_path(os.path.dirname(self.env.get("IRGEN_WORK_PATH")))
        self.init_logger()
        self.context.check_redis_cached_config()
        self.cache_db_handler = DBObjectPool.get_db_inst_by_name(name="filecache")
        self.gcc_db_handler = DBObjectPool.get_db_inst_by_name(name="gcc")
        self.clang_db_handler = DBObjectPool.get_db_inst_by_name(name="clang")
    
    def init_logger(self):
        capture_log_init(log_dir=self.context.LOG_DIR, log_mode="a", log_name="cache.log", log_level="DEBUG")
            
    def run_handler(self):
        change_files = [os.path.abspath(file) for file in sys.argv[1:] if os.path.exists(file)]
        logging.debug("Candidates cache files: %s" % ' '.join(change_files))
        gcc_name_dep = self.gcc_db_handler.get_name_dep()
        gcc_link_dep = self.gcc_db_handler.get_link_dep()
        clang_name_dep = self.clang_db_handler.get_name_dep()
        clang_link_dep = self.clang_db_handler.get_link_dep()
        
        change_files_md5 = [file_md5(file) for file in change_files]
        
        for index in range(len(change_files)):
            cache_file = ""
            src_md5 = change_files_md5[index]
            if src_md5 in gcc_name_dep.keys() and src_md5 not in gcc_link_dep.keys():
                cache_file = gcc_name_dep.get(src_md5, "")
            
            if src_md5 in clang_name_dep.keys() and src_md5 not in clang_link_dep.keys():
                cache_file = clang_name_dep.get(src_md5, "")
            
            if not cache_file:
                continue
            
            
            if not self.cache_db_handler.is_exists(src_md5):
                
                try:
                    logging.debug("Try to cache %s" % cache_file )
                    cache_name = os.path.join(self.context.CACHE_DIR, src_md5 + self.context.CACHE_EXT)
                    shutil.copy(cache_file, cache_name)
                except Exception as e:
                    logging.warning("Cache file %s failed" % cache_file)
                    print(e)
        
                self.cache_db_handler.set_cache_map(src_md5, cache_file)
        
    
if __name__ == "__main__":
    handler = FileChangeHandler()
    handler.init_runtime_env()
    handler.run_handler()